package org.geektimes.util;

/**
 * @Author: zhangsw
 * @CreateDate: 2021/3/17 16:56
 * @Description: java类作用描述
 * @UpdateUser: 更新者
 * @UpdateDate: 2021/3/17 16:56
 * @UpdateRemark: 更新说明
 * @Version: 1.0
 */

import org.apache.derby.iapi.store.raw.log.LogFactory;
import sun.rmi.runtime.Log;

import java.nio.charset.StandardCharsets;
import java.security.MessageDigest;
import java.security.NoSuchAlgorithmException;

/**
 * Created by Administrator on 2018/3/8.
 */
public class MD5 {

    private static final String algorithm = "MD5";
    public static String md5(String s) {
        try {
            MessageDigest md = MessageDigest.getInstance(algorithm);
            byte[] bytes = md.digest(s.getBytes(StandardCharsets.UTF_8));
            return toHex(bytes);
        }
        catch (Exception e) {
            throw new RuntimeException(e);
        }
    }
    public static String toHex(byte[] bytes) {

        final char[] HEX_DIGITS = "0123456789ABCDEF".toCharArray();
        StringBuilder ret = new StringBuilder(bytes.length * 2);
        for (int i=0; i<bytes.length; i++) {
            ret.append(HEX_DIGITS[(bytes[i] >> 4) & 0x0f]);
            ret.append(HEX_DIGITS[bytes[i] & 0x0f]);
        }
        return ret.toString();
    }

    public static String getMD5(String data){
        StringBuffer buf = new StringBuffer();
        try {
            MessageDigest md = MessageDigest.getInstance(algorithm);//【runqian 2017-07-17】sonar 空引用 bug 修复

            md.update(data.getBytes(StandardCharsets.UTF_8));

            byte[] byteDigest=null;
            if(md!=null){
                byteDigest = md.digest();
            }

            int i;
            if(byteDigest!=null && byteDigest.length>0){
                for (int offset = 0; offset < byteDigest.length; offset++) {
                    i = byteDigest[offset];
                    if (i < 0)
                        i += 256;
                    if (i < 16)
                        buf.append("0");
                    buf.append(Integer.toHexString(i));
                }
            }
        } catch (NoSuchAlgorithmException e) {
        }

        // 32位加密
        return buf.toString();
    }
}
